-- UIPetScrapSet
-- Create by cheny3
-- 冈布奥碎片设置界面

-- UIPetScrapSet继承自Layer
UIPetScrapSet = class("UIPetScrapSet", function()
    return cc.Layer:create();
end);

function UIPetScrapSet.create(campId)
    return UIPetScrapSet.new(campId);
end

-- 商品格最大行数和列数
local MAX_GRID_ROW    = 2;
local MIN_GRID_COLUMN = 3;


-- 内部函数声明

-- 构造函数
function UIPetScrapSet:ctor(campId)
    -- 初始化
    self:setName("UIPetScrapSet");

    local node = cc.CSLoader:createNode("layout/talent/TalentFruitBonus.csb");
    self:addChild(node);
    self.node = node;
    self.campId = campId;

    local CT = node:getChildByName("CT");
    local scrollview = CT:getChildByName("scrollview");
    local line1 = CT:getChildByName("line1");
    local line3 = CT:getChildByName("line3");
    scrollview:setVisible(false);
    line1:setVisible(false);
    line3:setVisible(true);

    scrollview = CT:getChildByName("scrollview2");
    self.CT = CT;
    self.scrollView = scrollview;
    self.scrollView:setVisible(true);
    self.oriHeight = self.scrollView:getInnerContainerSize().height;

    -- 修改滚动方向
    -- 1 垂直
    -- 2 水平
    self.scrollView:setDirection(1);

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UIPetScrapSet:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 重绘
function UIPetScrapSet:redraw()
    -- 标题
    local title1 = findChildByName(self.node, "CT/title1");
    title1:setVisible(true);
    local campName = CampM.query(self.campId, "name");
    title1:setString(campName);
    TextStyleM.setTitleStyle(title1);
    if not title1.posY then
        title1.posY = title1:getPositionY();
    end
    title1:setPositionY(title1.posY + 10);

    -- 副标题
    local title2 = findChildByName(self.node, "CT/title2");
    title2:setVisible(true);
    title2:getVirtualRenderer():setHorizontalAlignment(cc.TEXT_ALIGNMENT_CENTER);

    local kerning = -3;
    if not isFullWidthLang() then
        kerning = -1;
    end
    TextStyleM.setTextStyle(title2, TextStyleM.TEXT_SIZE_SMALL,
       TextStyleM.TEXT_COLOR_LIGHT_BLUE, true, nil, nil, nil, 18, nil, true);
    title2:getVirtualRenderer():setAdditionalKerning(getLocKerning() + kerning);
    title2:setString(getLocStr("slime_set_explain"));

    if getLang() ~= "zh" and getLang() ~= "tw" then
        title2:setPositionY(title2:getPositionY() + 10);
    end

    -- 绘制内容
    self:redrawSlimeLines();
end

-- 绘制Top横线
-- 为了防止滚动穿帮，先这么处理
function UIPetScrapSet:redrawTopLines(totalHeight)
    local lineNode = cc.CSLoader:createNode("layout/setting/NotifyNode.csb");
    local widget = replaceNodeWithWidget(lineNode);

    local child = widget:clone();
    local line = child:getChildByName("line");

    for _, node in pairs(child:getChildren()) do
        node:setVisible(false);
    end
    line:setScale(1);
    line:setVisible(true);
    child:setAnchorPoint(cc.p(0.5, 0.5));
    child:setPositionX(25);
    child:setPositionY(totalHeight - 25);

    self.scrollView:addChild(child);
end

-- 绘制冈布奥条目
function UIPetScrapSet:redrawSlimeLines()
    -- 去除所有
    self.scrollView:removeAllChildren();

    local lineNode = cc.CSLoader:createNode("layout/setting/NotifyNode.csb");
    local widget = replaceNodeWithWidget(lineNode);

    -- 获取阵营稀有冈布奥
    local setType = FormulaM.invoke("CALC_POT_PET_RANGE", "gem");
    local slimeList = {};
    for _, slimeType in pairs(setType) do
        slimeList = table.append(slimeList, PetM.getTypeSlimeListByCamp(self.campId, slimeType));
    end

    -- 活动部分
    slimeList = table.append(slimeList, PetM.getActivitySlimeListByCamp(self.campId));

    table.sort(slimeList);

    -- 当前剩余没有关闭
    self.leftOpenNum = #slimeList;

    -- 计算容器高度
    local needHeight = #slimeList * 60 + 30;
    local totalHeight = math.max(self.oriHeight, needHeight);

    self.scrollView:setInnerContainerSize(cc.size(self.scrollView:getInnerContainerSize().width, totalHeight));

    -- 绘制顶部横线
    self:redrawTopLines(totalHeight);

    -- 玩家特殊设置
    self.slimeSet = table.deepcopy(ME.user.dbase:query("rare_slime_setting") or {});

    for i = 1, #slimeList do
        local child = widget:clone();
        local icon = child:getChildByName("icon");
        local text =  child:getChildByName("text");
        local bubble = child:getChildByName("bubble");
        local line = child:getChildByName("line");
        line:setScaleX(1);

        local y = (i - 1) * -60 + totalHeight - 80;
        child:setPositionX(25);
        child:setPositionY(y);
        child:setVisible(true);

        local iconPath = getSmallHeroIconPath(slimeList[i]);
        icon:loadTexture(iconPath);
        icon:setPosition(cc.p(icon:getPositionX() - 15, icon:getPositionY() - 8));
        local heroName = PetM.query(slimeList[i], "name");
        TextStyleM.setTextStyle(text, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
        text:setString(heroName);

        -- 显示星星
        local maxStarNum = 5;
        local curStar = 0;
        local pet = PetM.getMyPet(slimeList[i]);
        local hasEquip = false;
        bubble:setVisible(false);
        bubble:setPositionX(bubble:getPositionX() + 30);

        if pet then
            -- 有冈布奥
            curStar = pet:getRank();
            hasEquip = EquipM.getHeroEquip(pet, EQUIP_TYPE_MEDAL, 1);
        end

        if curStar < maxStarNum or not hasEquip then
            -- 绘制星星
            local tStar = createStarLayerEx(curStar, maxStarNum, "images/ui/symbol/star_large.png",
                    "images/ui/symbol/star_large2.png","right", -0.7, true);
            tStar:setPosition(cc.p(bubble:getPositionX() - 60, bubble:getPositionY() - 20));
            tStar:setScale(0.9);
            child:addChild(tStar);
        else
            bubble:setVisible(true);
            if self.slimeSet[slimeList[i]] and self.slimeSet[slimeList[i]] == 1 then
                -- 设置了关闭
                bubble:loadTexture(getSettingIconPath("system", "close"));
                TextStyleM.setTextStyle(text, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_RED);
                self.slimeSet[slimeList[i]] = 1;
                self.leftOpenNum = self.leftOpenNum - 1;
            else
                -- 默认或设置了开启
                bubble:loadTexture(getSettingIconPath("system", "open"));
                TextStyleM.setTextStyle(text, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
                self.slimeSet[slimeList[i]] = 0;
            end
        end

        local function onClick(sender, eventType)
            -- 点击时的回调
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_click");
                if self.slimeSet[slimeList[i]] == 1 then
                    self.leftOpenNum = self.leftOpenNum + 1;
                    -- 关闭->开启
                    self.slimeSet[slimeList[i]] = 0;
                    alert(string.format(getLocStr("open_slime_gold_tank"), heroName));
                    bubble:loadTexture(getSettingIconPath("system", "open"));
                    TextStyleM.setTextStyle(text, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
                else
                    -- 剩余没有关闭的
                    -- SLIMEC-4384 策划需求可以全部关闭
                    -- if self.leftOpenNum <= 1 then
                    --     alert(getLocStr("scrap_limit_set_tip"));
                    --     return;
                    -- end

                    self.leftOpenNum = self.leftOpenNum - 1;
                    -- 开启->关闭
                    self.slimeSet[slimeList[i]] = 1;
                    alert(string.format(getLocStr("close_slime_gold_tank"), heroName));
                    bubble:loadTexture(getSettingIconPath("system", "close"));
                    TextStyleM.setTextStyle(text, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_RED);
                end
            end
        end
        bubble:addTouchEventListener(onClick);

        self.scrollView:addChild(child);
    end
end

-- 注册事件处理回调函数
function UIPetScrapSet:registerEventCallback()
    -- 注册获得焦点的回调
    EventMgr.register("UIPetScrapSet", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIPetScrapSet" then
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_GEM);
        end
    end);

    -- 活动开始事件
    EventMgr.register("UIPetScrapSet", event.ACTIVITY_CHANGE, function(args)
        local id = args["id"];
        if ActivityM.query(id, "rule") ~= "dungeon" then
            -- 不是地面迷宫
            return;
        end

        -- 重绘
        self:redraw();
    end);

    -- 活动结束事件
    EventMgr.register("UIPetScrapSet", event.ACTIVITY_CLOSE, function(args)
        local id = args["id"];
        if ActivityM.query(id, "rule") ~= "dungeon" then
            -- 不是地面迷宫
            return;
        end

        -- 重绘
        self:redraw();
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UIPetScrapSet 界面析构清理");
            EventMgr.removeAll("UIPetScrapSet");
            local uiPetShop = UIMgr.getCurrentScene():getFormByName("UIPetShop");
            if uiPetShop then
                -- 显示兑换界面
                uiPetShop:setVisible(true);
            end
        elseif eventType == "enter" then
            local uiPetShop = UIMgr.getCurrentScene():getFormByName("UIPetShop");
            if uiPetShop then
                -- 隐藏兑换界面
                uiPetShop:setVisible(false);
            end
        end
    end);
end

-- 注册点击事件
function UIPetScrapSet:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 发送更改
            local rareSlimeSet = ME.user.dbase:query("rare_slime_setting") or {};
            -- 是否修改了
            local change = false;
            for pet_id, closeFlag in pairs(self.slimeSet) do
                if not rareSlimeSet[pet_id] or rareSlimeSet[pet_id] ~= closeFlag then
                    change = true;
                    break;
                end
            end

            if change then
                -- 发送修改命令
                Operation.cmd_update_rare_slime_setting(self.slimeSet);
            end

            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIPetScrapSet");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 更多按钮
    local btnSet = findChildByName(self.node, "BT/take_bonus");
    btnSet:setVisible(false);
end